package com.poposchool.project.controller;


import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.poposchool.project.common.Constants;
import com.poposchool.project.common.Result;
import com.poposchool.project.controller.dto.UserDTO;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.poposchool.project.service.ITotalUserService;
import com.poposchool.project.entity.TotalUser;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wangjie
 * @since 2022-09-09
 */
@Api(tags = "用户管理")
@RestController
@RequestMapping("/user")
public class TotalUserController {

    @Resource
    private ITotalUserService totalUserService;

    @GetMapping("/userCounts")
    public Result getCounts(){
        return Result.success(totalUserService.count());
    }

    @PostMapping("/login")
    //拿到用户的头像和昵称
    public Result login(@RequestBody UserDTO userDTO){
        String userName = userDTO.getUserName().trim();
        String passWord = userDTO.getPassWord().trim();
        //都是空，就不用查数据库了
        if (StrUtil.isBlank(userName) || StrUtil.isBlank(passWord)){
            return Result.error(Constants.CODE_400,"参数错误",null);
        }
        return Result.success(Constants.CODE_200,"登入成功",totalUserService.login(userDTO));
    }

    @PostMapping("/register")
    public Result register(@RequestBody UserDTO userDTO){
        String userName = userDTO.getUserName().trim();
        String passWord = userDTO.getPassWord().trim();
        if (StrUtil.isBlank(userName) || StrUtil.isBlank(passWord)){
            return Result.error(Constants.CODE_400,"参数错误",null);
        }
        TotalUser user = totalUserService.register(userDTO);
        return Result.success(Constants.CODE_200,"注册成功",null);
    }

    @GetMapping("/users")
    public List<TotalUser> findAll() {
        return totalUserService.list();
    }

    @GetMapping("/user")
    public TotalUser findOne(Integer id) {
        return totalUserService.getById(id);
    }

    // 新增或者更新
    @PostMapping("/save")
    public boolean save(@RequestBody TotalUser totalUser) {
        if (totalUser.getUsername() == null || totalUser.getUsername().equals("")){
            return false;
        }
        if (!judgeUserName(totalUser.getUsername())){
            return false;
        }
        totalUser.setCreateTime(LocalDateTime.now());
        return totalUserService.save(totalUser);
    }

    @PostMapping("/update")
    public boolean update(@RequestBody TotalUser totalUser) {
        return totalUserService.updateById(totalUser);
    }

    @GetMapping("/pageUsers")
    public Page<TotalUser> findPage(@RequestParam Integer pageNum,
                                    @RequestParam Integer pageSize,
                                    @RequestParam(defaultValue = "") String username,
                                    @RequestParam(defaultValue = "") String city,
                                    @RequestParam(defaultValue = "") String province) {
        QueryWrapper<TotalUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        return totalUserService.findPage(new Page<>(pageNum, pageSize), username,city,province);
    }

    @DeleteMapping("/deleteUser")
    public Boolean delete(Integer id) {
        return totalUserService.removeById(id);
    }

    @GetMapping("/judgeUserName")
    public Boolean judgeUserName(String username){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",username);
        TotalUser totalUser = totalUserService.getOne(queryWrapper);
        if (totalUser == null){
            return true;
        }else {
            return false;
        }

    }

    @PostMapping("/batchDeleteUsers")
//    参数类型不对，@RequestBody 后面用Map或者是javabean
    public void batchDeleteUsers(@RequestBody Map<String,List<Integer>> ids){
        if (ids.get("ids").size() == 0){
            return;
        }
        totalUserService.removeByIds(ids.get("ids"));
    }

    //excel导出
    @GetMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<TotalUser> list = totalUserService.list();
        // 通过工具类创建writer 写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("id", "ID");
        writer.addHeaderAlias("avatarId", "头像id");
        writer.addHeaderAlias("email", "邮箱");
        writer.addHeaderAlias("enabled", "是否使用");
        writer.addHeaderAlias("password", "密码");
        writer.addHeaderAlias("username", "用户名");
        writer.addHeaderAlias("deptId", "部门ID");
        writer.addHeaderAlias("phone", "电话");
        writer.addHeaderAlias("lastPasswordResetTime", "修改密码最后时间");
        writer.addHeaderAlias("nickName", "昵称");
        writer.addHeaderAlias("gender", "性别()性别：1.男，2.女，0.未知");
        writer.addHeaderAlias("updateTime", "信息更新日期");
        writer.addHeaderAlias("city", "城市");
        writer.addHeaderAlias("province", "省份");
        writer.addHeaderAlias("country", "国家");
        writer.addHeaderAlias("createTime", "注册时间");
        writer.addHeaderAlias("status", "用户身份:0.超级管理员，1.管理员，2.普通用户");

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();

    }

//    //excel导入
//    @PostMapping("/importExcel")
//    public Boolean importExcel(MultipartFile file) throws IOException {
//        InputStream inputStream = file.getInputStream();
//        ExcelReader reader = ExcelUtil.getReader(inputStream);
//
//        //方式1：通过JavaBean的方式读取excel内的对象，但是要求表头必须市英文，和JavaBean属性对应
////        List<User> users = reader.readAll(User.class);
//
//        //方式二：忽略表头中文，直接获取表格数据
//        List<List<Object>> list = reader.read(1);
//        List<User> users = CollUtil.newArrayList();
//
//        for(List<Object> row:list){
//            TotalUser user =new TotalUser();
//            user.setUserName(row.get(0).toString());
//            user.setPassWord(row.get(1).toString());
//            user.setNickName(row.get(2).toString());
//            user.setEmail(row.get(3).toString());
//            user.setPhone(row.get(4).toString());
//            user.setAddress(row.get(5).toString());
//            user.setCreateTime(new Date());
////            user.setAvatarUrl(row.get(6).toString());
//            users.add(user);
//        }
//        //将excel导入的数据保存到数据库
//        totalUserService.save(users);
//        return true;
//    }


}

